package com.supermarket.config.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.supermarket.common.ResponseResult;
import com.supermarket.entity.User;
import com.supermarket.service.UserService;
import com.supermarket.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

/**
 * JWT认证拦截器
 */
@Component
public class JwtAuthInterceptor implements HandlerInterceptor {
    
    private final ObjectMapper objectMapper = new ObjectMapper();
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @Autowired
    private UserService userService;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求URI
        String requestURI = request.getRequestURI();
        
        // 打印详细请求信息
        System.out.println("\n======== JWT认证拦截器 ========");
        System.out.println("请求URI: " + requestURI);
        System.out.println("请求方法: " + request.getMethod());
        
        // 特别检查category.json
        if ("/category.json".equals(requestURI)) {
            System.out.println("检测到category.json请求，直接放行");
            System.out.println("===========================");
            return true;
        }
        
        // 检查是否为静态资源请求
        boolean isStaticResource = requestURI.startsWith("/uploads/") || 
                                   requestURI.startsWith("/static/") ||
                                   requestURI.contains("/uploads/") ||
                                   requestURI.contains("/static/") ||
                                   requestURI.startsWith("/commodities/") ||
                                   requestURI.startsWith("/article/") ||
                                   requestURI.endsWith(".json") ||
                                   requestURI.endsWith(".js") ||
                                   requestURI.endsWith(".css") ||
                                   requestURI.endsWith(".html") ||
                                   requestURI.endsWith(".ico") ||
                                   requestURI.endsWith(".png") ||
                                   requestURI.endsWith(".jpg") ||
                                   requestURI.endsWith(".gif") ||
                                   requestURI.endsWith(".svg") ||
                                   requestURI.endsWith(".ttf") ||
                                   requestURI.endsWith(".woff") ||
                                   requestURI.endsWith(".woff2") ||
                                   requestURI.endsWith(".eot");
        
        // 静态资源不需要验证JWT
        if (isStaticResource) {
            System.out.println("检测到静态资源请求，跳过JWT验证");
            System.out.println("资源类型: " + (requestURI.contains(".") ? requestURI.substring(requestURI.lastIndexOf(".")) : "目录"));
            System.out.println("===========================");
            return true;
        }
        
        // 检查是否为排除的API路径
        boolean isExcludedApi = requestURI.equals("/login") ||
                               requestURI.equals("/register") ||
                               requestURI.equals("/logout") ||
                               requestURI.equals("/stats") ||
                               requestURI.startsWith("/order/stats/") ||
                               requestURI.startsWith("/user/alluser/") ||
                               requestURI.equals("/user/selectByID");
        
        // 排除的API不需要验证JWT
        if (isExcludedApi) {
            System.out.println("检测到排除的API请求，跳过JWT验证");
            System.out.println("===========================");
            return true;
        }
        
        // 获取请求头中的Authorization
        String authHeader = request.getHeader("Authorization");
        System.out.println("Authorization头: " + (authHeader != null ? authHeader.substring(0, Math.min(20, authHeader.length())) + "..." : "null"));
        
        // 如果请求头中没有Authorization信息，或者不是以Bearer开头，则返回未认证错误
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            System.out.println("未提供有效的Authorization头");
            System.out.println("===========================");
            responseUnauthorized(response, "请先登录");
            return false;
        }
        
        // 提取token
        String token = authHeader.substring(7);
        
        if (!StringUtils.hasText(token)) {
            System.out.println("token为空");
            System.out.println("===========================");
            responseUnauthorized(response, "无效的token");
            return false;
        }
        
        // 验证token
        try {
            boolean valid = jwtUtil.validateToken(token);
            if (!valid) {
                System.out.println("token已过期");
                System.out.println("===========================");
                responseUnauthorized(response, "token已过期，请重新登录");
                return false;
            }
            
            // 提取用户ID和角色
            Integer userId = jwtUtil.getUserIdFromToken(token);
            String role = jwtUtil.getRoleFromToken(token);
            
            System.out.println("token验证成功，用户ID: " + userId + ", 角色: " + role);
            
            if (userId == null) {
                System.out.println("从token中无法获取用户ID");
                System.out.println("===========================");
                responseUnauthorized(response, "无效的token");
                return false;
            }
            
            // 根据用户ID获取用户信息
            User user = userService.getUserById(userId);
            if (user == null) {
                System.out.println("未找到用户，ID: " + userId);
                System.out.println("===========================");
                responseUnauthorized(response, "用户不存在");
                return false;
            }
            
            // 将用户信息存储到会话中，以便与现有代码兼容
            HttpSession session = request.getSession();
            session.setAttribute("currentUser", user);
            
            // 将用户信息存储到请求属性中，可以在Controller中使用
            request.setAttribute("userId", userId);
            request.setAttribute("role", role);
            
            System.out.println("验证通过，用户: " + user.getUsername() + ", 角色: " + role);
            System.out.println("===========================");
            
            return true;
        } catch (Exception e) {
            System.out.println("token验证异常: " + e.getMessage());
            e.printStackTrace();
            System.out.println("===========================");
            responseUnauthorized(response, "token验证失败: " + e.getMessage());
            return false;
        }
    }
    
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 请求完成后处理
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 整个请求结束后的处理
    }
    
    /**
     * 返回未授权的错误响应
     */
    private void responseUnauthorized(HttpServletResponse response, String message) throws Exception {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json;charset=UTF-8");
        ResponseResult<String> result = ResponseResult.error(401, message);
        response.getWriter().write(objectMapper.writeValueAsString(result));
    }
}